<?php

namespace App\Services\Base;
use App\Common\ResponseCode;
use App\Common\Tools;
use App\Exceptions\BusinessException;
use App\Params\Backend\PayListParam;
use App\Params\Backend\PayUpdateParam;
use App\Repository\PayRepository;
use App\Services\BaseService;

/**
 * 支付相关业务类
 *
 * @author WangBin
 * @date 2022-01-19
 * @package App\Http\Services
 */
class PayService extends BaseService
{
    /**
     * 查询支付方式列表
     *
     * @param PayListParam $param
     * @return array
     */
    public function getList(PayListParam $param)
    {
        $result = PayRepository::getInstance()->getList($param->toArray());
        return $this->toList($result, $param->getPage(), $param->getPageSize());
    }

    /**
     * 更新支付方式
     *
     * @param PayUpdateParam $param
     * @return int|mixed
     * @throws BusinessException
     */
    public function update(PayUpdateParam $param)
    {
        $data = $param->toArray();
        if($param->getPayId()) {
            $payment = PayRepository::getInstance()->getById($param->getPayId());
            if(is_null($payment)) {
                throw new BusinessException(ResponseCode::PAYMENT_NOT_FOUND);
            }
        } else {
            $data['pay_id'] = Tools::nextId();
        }

        $checkExist = PayRepository::getInstance()->checkKeyExist($param->getPayKey(), $param->getPayId());
        if($checkExist) {
            throw new BusinessException(ResponseCode::PAYMENT_KEY_EXIST);
        }
        return PayRepository::getInstance()->save($data, $param->getPayId());
    }

    /**
     * 获取支付方式详情
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws BusinessException
     */
    public function getInfo(int $id)
    {
        $payment = PayRepository::getInstance()->getById($id);
        if(is_null($payment)) {
            throw new BusinessException(ResponseCode::PAYMENT_NOT_FOUND);
        }
        return $payment;
    }
}
